/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package modules.enderecamento.gui.custom;

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
/**
 *
 * @author Clezio
 */
public class LimitedIntegerJTextField extends WMSJTextField{

    public LimitedIntegerJTextField(int maxLength) {
        super(maxLength);
        this.addKeyListener(new KeyListener() {

            public void keyTyped(KeyEvent e) {
                char c = e.getKeyChar();
                if (!Character.isDigit(c) && KeyEvent.VK_BACK_SPACE != c) {
                    e.consume();
                }
            }

            public void keyPressed(KeyEvent e) {
            }

            public void keyReleased(KeyEvent e) {
            }
        });
    }
    private String oldValue;

    public void paste() {
        this.oldValue = getText();
        super.paste();
        if (!isNumeros(getText())) {
            setText(this.oldValue);
        }
    }

    /**
     * Obtem uma string que representa os números digitados no campo, e verifica se na string
     * possui apenas números.
     * @param valor
     * @return
     */
    private boolean isNumeros(String valor) {
        final String NUMEROS = "0123456789";
        for (int i = 0; i < valor.length(); i++) {
            char caracter = valor.charAt(i);
            if (NUMEROS.indexOf(caracter) == -1) {
                return false;
            }
        }
        return true;
    }
}
